// TypeScript file
class TestShader1 extends eui.Component {
    pImg: eui.Image;
    sliCenx: eui.HSlider;
    sliCeta: eui.HSlider;
    lblkCenX: eui.Label;
    lblPCeta: eui.Label;

    constructor() {
        super();
        this.addEventListener(eui.UIEvent.COMPLETE, this.onComplete, this)
        this.skinName = Test
        this.horizontalCenter = this.verticalCenter = 0
    }

    onComplete() {
        this.removeEventListener(eui.UIEvent.COMPLETE, this.onComplete, this)
        this.initConfig()
        this.sliCenx.addEventListener(eui.UIEvent.CHANGE, this.changeHandler, this);
        this.sliCeta.addEventListener(eui.UIEvent.CHANGE, this.changeHandler, this)
        this.initShader()
        this.changeHandler()
    }

    initConfig() {
        this.sliCenx.minimum = 0
        this.sliCenx.maximum = 100
        this.sliCenx.value = 50

        this.sliCeta.minimum = 0
        this.sliCeta.maximum = 100
        this.sliCeta.value = 50
    }

    changeHandler() {
        this.lblkCenX.text = "centerX[0-1] " + this.sliCenx.value / 100
        this.lblPCeta.text = "pcita[0-1] " + this.sliCeta.value / 100
        this.updateShaderParams()
    }

    initShader() {
        let vertexSrc = `
            attribute vec2 aVertexPosition;
            attribute vec2 aTextureCoord;
            attribute vec2 aColor;

            uniform vec2 projectionVector;

            varying vec2 vTextureCoord;
            varying vec4 vColor;

            const vec2 center = vec2(-1.0, 1.0);

            void main(void) {
                gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);
                vTextureCoord = aTextureCoord;
                vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);
            }
        `;

        let fragmentSrc = `
            precision lowp float;
            varying vec2 vTextureCoord;
            varying vec4 vColor;
            uniform sampler2D uSampler;

            uniform float ceta;
            uniform float centerX;

            void main() {
                vec2 uv = vTextureCoord.xy;
                float centerY = -1.0;
                float scaleRate = uv.y/2.0 + 0.5;
                uv.x = (uv.x - centerX)/scaleRate + centerX;
                vec2 texCoord = uv;
                gl_FragColor = texture2D(uSampler, texCoord);
            }
        `;
        let fliter = new egret.CustomFilter(vertexSrc, fragmentSrc, { ceta: this.sliCeta.value / 100, centerX: this.sliCenx.value / 100 })
        this.pImg.filters = [fliter]
    }

    updateShaderParams() {
        if (this.pImg.filters && this.pImg.filters[0]) {
            let filter: egret.CustomFilter = <any>this.pImg.filters[0]
            filter.uniforms.ceta = this.sliCeta.value / 100
            filter.uniforms.centerX = this.sliCenx.value / 100
            this.pImg.filters = [filter]
        }
    }
}